$(function() {
	// 初始化单选框样式
	$('.radio-box input').iCheck({
		checkboxClass: 'icheckbox-blue',
		radioClass: 'iradio-blue',
		increaseArea: '20%'
	});
	// 全部商品/指定商品 状态变为checked时触发
	$("input[type='radio'][name='fullActiveScope']").on('ifChecked', fullActiveScopeChecked); 
	activeTypeChange();
	setBuyProNum();
	setfullProNum();
	setRulePresentNum();
});

/**
 * 弹出筛选商品页面
 */
function toAddProduct() {
	var url = path + "/presentActivityController/to_add_product";
	var activityType = $("#activityType").val();
	if(activityType == "5") { // 满赠
		// 添加排除掉的商品ID
		$("#fullProTbody").find("td[id^='fullProTd_id_']").each(function(){
			if(url.indexOf("?") > -1) {
				url += "&excludeIds=" + $(this).text();
			} else {
				url += "?excludeIds=" + $(this).text();
			}
		});
	}
	openLayer("发布活动 > 筛选商品", url);
}

/**
 * 添加商品窗口回调函数
 * @param productArr 被选中的商品信息
 */
function getAddProductInfo(productArr) {
	if(productArr && productArr.length > 0) {
		var activityType = $("#activityType").val();
		if(activityType == "4") { // 买赠
			addBuyPro(productArr);
		} else if (activityType == "5") { // 满赠
			addFullPro(productArr);
		}
	}
}

/**
 * 买赠-添加商品
 * @param productArr
 */
function addBuyPro(productArr) {
	var trHtml = "";
	for(var i = 0, j = productArr.length; i < j; i ++) {
		var obj = productArr[i];
		buyProSize ++;
		var trId = "buyProTr_" + buyProSize;
		trHtml += "<tr id = '" + trId + "'>";
		trHtml += "<td id='buyProTd_id_" + buyProSize + "'>" + obj.id + "</td>";
		trHtml += "<td id='buyProTd_name_" + buyProSize + "'>" + obj.name + "</td>";
		trHtml += "<td id='buyProTd_payOneMileage_" + buyProSize + "'>" + obj.payOneMileage + "</td>";
		trHtml += "<td id='buyProTd_saleNum_" + buyProSize + "' style='padding: 4px;'><input id='buyPro_saleNum_" + buyProSize + "' value='1' class='input-text radius size-S' style='text-align:center;ime-mode:Disabled' onkeyup=\"value=value.replace(/[^\\d]/g,'')\" ondrop='return false;' maxlength='12'/></td>";
		trHtml += "<td id='buyProTd_preId_" + buyProSize + "'></td>"; // 赠品编号
		trHtml += "<td id='buyProTd_preName_" + buyProSize + "'></td>"; // 赠品名称
		trHtml += "<td id='buyProTd_preNum_" + buyProSize + "' style='padding: 4px;'></td>"; // 赠品数量
		trHtml += "<td>";
		trHtml += "<a href='javascript:;' class='btn-link' onclick='buy_toAddPresent(\"" + trId + "\");'>赠品</a>&nbsp;&nbsp;";
		trHtml += "<a href='javascript:;' class='btn-link' style='color: red;' onclick='deleteDomById(\"" + trId + "\");'>删除</a>";
		trHtml += "</td>";
        trHtml += "</tr>"
	}
	$("#buyProTbody").append(trHtml);
	setBuyProNum();
}

/**
 * 满赠-选择指定商品-添加商品
 * @param productArr
 */
function addFullPro(productArr) {
	var trHtml = "";
	for(var i = 0, j = productArr.length; i < j; i ++) {
		var obj = productArr[i];
		var trId = "fullProTr_" + obj.id;
		trHtml += "<tr id='" + trId + "'>";
		trHtml += "<td id='fullProTd_id_" + obj.id + "'>" + obj.id + "</td>";
		trHtml += "<td>" + obj.name + "</td>";
		trHtml += "<td>" + obj.prodType + "</td>";
		trHtml += "<td>" + obj.mercName + "</td>";
		trHtml += "<td>" + obj.storeNum + "</td>";
		trHtml += "<td>" + obj.payCostMileage + "</td>";
		trHtml += "<td>" + obj.payOneMileage + "</td>";
		trHtml += "<td>";
		trHtml += "<a href='javascript:;' style='color: red;' onclick='deleteDomById(\"" + trId + "\");'>删除</a>";
		trHtml += "</td>";
        trHtml += "</tr>"
	}
	$("#fullProTbody").append(trHtml);
	setfullProNum();
}

var g_trId; // 买赠活动-添加赠品时被操作的行ID
/**
 * 买赠活动-弹出添加赠品筛选框
 * @param trId
 */
function buy_toAddPresent(trId) {
	g_trId = trId;
	openLayer("发布活动 > 筛选赠品", path + "/presentActivityController/to_add_present?isShowApplyAllFlag=true");
}

var ruleTbodyId;
/**
 * 满赠活动-弹出赠品筛选框
 * @param tbodyId
 */
function full_toAddPresent(tbodyId) {
	ruleTbodyId = tbodyId;
	url = path + "/presentActivityController/to_add_present?isShowApplyAllFlag=false";
	var activityType = $("#activityType").val();
	if(activityType == "5") { // 满赠
		// 添加排除掉的赠品ID
		//var tdIdPrefix = "rulePresentTd_id_" + tbodyId.split("_")[1] + "_";
		$("table[id^='rulePresentTb']").find("td[id^='rulePresentTd_id_']").each(function(){
			url += "&excludeIds=" + $(this).text();
		});
	}
	openLayer("发布活动 > 筛选赠品", url);
}

/**
 * 添加赠品-回调函数
 * @param presentArr
 * @param applyAllFlag
 */
function getAddPresentInfo(presentArr, applyAllFlag) {
	if(presentArr && presentArr.length > 0) {
		var activityType = $("#activityType").val();
		if(activityType == "4") { // 买赠
			addBuyPresent(presentArr, applyAllFlag);
		} else if (activityType == "5") { // 满赠
			addFullPreset(presentArr);
		}
	}
}

/**
 * 买赠活动-添加赠品
 * @param productArr
 * @param applyAllFlag
 */
function addBuyPresent(presentArr, applyAllFlag) {
	// 处理第一行赠品信息
	var present = presentArr[0];
	var idFlag = g_trId.split("_")[1];
	if($("#buyProTd_preId_" + idFlag).text() == "") {
		buyPreReplaceRow(present, idFlag);
	} else { // 该行已经有数据，则增加一行
		buyPreCopyRow(present, idFlag);
	}
	// 处理其他行赠品信息
	if(applyAllFlag) { // 应用到其他待选商品
		var trArr = $("#buyProTbody").find("tr");
		trArr.each(function() { // 给空行增加赠品信息
			var trId = $(this).attr("id");
			idFlag = trId.split("_")[1];
			if($("#buyProTd_preId_" + idFlag).text() == "") {
				buyPreReplaceRow(present, idFlag);
			}
		});
	} else {
		var tmpFlag = idFlag;
		for(var i = 1, j = presentArr.length; i < j; i ++) {
			present = presentArr[i];
			tmpFlag = buyPreCopyRow(present, tmpFlag);
		}
	}
}

/**
 * 买赠-根据赠品信息显示到对应行
 * @param present
 * @param idFlag
 */
function buyPreReplaceRow(present, idFlag) {
	$("#buyProTd_preId_" + idFlag).text(present.id); // 赠品编号
	$("#buyProTd_preName_" + idFlag).text(present.name); // 赠品名称
	$("#buyProTd_preNum_" + idFlag).html("<input class='input-text radius size-S' value='1' id='buyPro_preNum_" + idFlag + "' style='text-align:center;ime-mode:Disabled' onkeyup=\"value=value.replace(/[^\\d]/g,'')\" ondrop='return false;' maxlength='12'/>"); // 赠品数量
}

/**
 * 买赠-根据选中的赠品增加一行数据
 * @param present
 * @param idFlag 被拷贝的行标识
 * @returns 新增行的行标识
 */
function buyPreCopyRow(present, idFlag) {
	buyProSize ++;
	var trId = "buyProTr_" + buyProSize;
	var trHtml = "<tr id = '" + trId + "'>";
	trHtml += "<td id='buyProTd_id_" + buyProSize + "'>" + $("#buyProTd_id_" + idFlag).text() + "</td>";
	trHtml += "<td id='buyProTd_name_" + buyProSize + "'>" + $("#buyProTd_name_" + idFlag).text() + "</td>";
	trHtml += "<td id='buyProTd_payOneMileage_" + buyProSize + "'>" + $("#buyProTd_payOneMileage_" + idFlag).text() + "</td>";
	trHtml += "<td id='buyProTd_saleNum_" + buyProSize + "' style='padding: 4px;'><input class='input-text radius size-S' value='1' id='buyPro_saleNum_" + buyProSize + "' style='text-align:center;ime-mode:Disabled' onkeyup=\"value=value.replace(/[^\\d]/g,'')\" ondrop='return false;' maxlength='12'/></td>";
	trHtml += "<td id='buyProTd_preId_" + buyProSize + "'>" + present.id + "</td>"; // 赠品编号
	trHtml += "<td id='buyProTd_preName_" + buyProSize + "'>" + present.name + "</td>"; // 赠品名称
	trHtml += "<td id='buyProTd_preNum_" + buyProSize + "' style='padding: 4px;'><input class='input-text radius size-S' value='1' id='buyPro_preNum_" + buyProSize + "' style='text-align:center;ime-mode:Disabled' onkeyup=\"value=value.replace(/[^\\d]/g,'')\" ondrop='return false;' maxlength='12'/></td>"; // 赠品数量
	trHtml += "<td>";
	trHtml += "<a href='javascript:;' class='btn-link' onclick='buy_toAddPresent(\"" + trId + "\");'>赠品</a>&nbsp;&nbsp;";
	trHtml += "<a href='javascript:;' class='btn-link' style='color: red;' onclick='deleteDomById(\"" + trId + "\");'>删除</a>";
	trHtml += "</td>";
    trHtml += "</tr>"
	$("#buyProTr_" + idFlag).after(trHtml);
    return buyProSize;
}

/**
 * 在规则中添加赠品
 * @param presentArr
 */
function addFullPreset(presentArr) {
	var trHtml = "";
	var ruleIndex = ruleTbodyId.split("_")[1];
	for(var i = 0, j = presentArr.length; i < j; i ++) {
		var obj = presentArr[i];
		var trId = "rulePresentTr_" + ruleIndex + "_" + obj.id;
		trHtml += "<tr id='" + trId + "'>";
		trHtml += "<td id='rulePresentTd_id_" + ruleIndex + "_" + obj.id + "'>" + obj.id + "</td>";
		trHtml += "<td>" + obj.name + "</td>";
		trHtml += "<td>" + obj.mercName + "</td>";
		trHtml += "<td>" + obj.stock + "</td>";
		trHtml += "<td style='padding: 4px;'><input class='input-text radius size-S' value='1' id='rulePresent_preNum_" + ruleIndex + "_" + obj.id + "' style='text-align:center;ime-mode:Disabled' onkeyup=\"value=value.replace(/[^\\d]/g,'')\" ondrop='return false;' maxlength='12'/></td>"; // 赠品数量
		trHtml += "<td>";
		trHtml += "<a href='javascript:;' style='color: red;' onclick='deleteDomById(\"" + trId + "\");'>删除</a>";
		trHtml += "</td>";
        trHtml += "</tr>"
	}
	$("#" + ruleTbodyId).append(trHtml);
	setRulePresentNum();
}

/**
 * 添加规则
 */
function addRule() {
	ruleNum ++;
	var tbHtml = '<table id="ruleTb_' + ruleNum + '" name="ruleTb" class="table" style="padding: 0px; margin: 0px;" cellpadding="0" cellspacing="0">';
	tbHtml += '<tr><td colspan="3" style="font-weight: bold;font-size: 15px;padding: 5px 0px 0px 5px;">规则' + ruleNum + '：';
	tbHtml += '<input type="button" class="btn btn-danger radius size-S" onclick="deleteDomById(\'ruleTb_' + ruleNum + '\');" value="删除规则"/>';
	tbHtml += '</td></tr>';
	tbHtml += '<tr>';
	tbHtml += '<td style="width: 14%;">订单金额：</td>';
	tbHtml += '<td style="width: 30%;"><input id="orderPrice_' + ruleNum + '" class="input-text radius size-S" style="ime-mode:disabled" onkeyup="value=value.replace(/[^\\d]/g,\'\')" ondrop="return false;" maxlength="12"/></td>';
	tbHtml += '<td style="width: 56%;"><font color="red">*</font>&nbsp;请输入订单金额（公里）</td>';
	tbHtml += '</tr>';
	tbHtml += '<tr>';
	tbHtml += '<td>活动赠品：</td>';
	tbHtml += '<td><input type="button" class="btn btn-primary radius size-S" onclick="full_toAddPresent(\'rulePresentTbody_' + ruleNum + '\');" value="添加赠品"/>';
	tbHtml += '&nbsp;您已选择&nbsp;<strong id="rulePreNum_' + ruleNum + '" style="font-size: 14px;">0</strong>&nbsp;款赠品';
	tbHtml += '</td>';
	tbHtml += '<td></td>';
	tbHtml += '</tr>';
	tbHtml += '<tr>';
	tbHtml += '<td></td>';
	tbHtml += '<td colspan="2">';
	tbHtml += '<div class="text-c">';
	tbHtml += '<table id="rulePresentTb_' + ruleNum + '" class="table table-border table-bordered table-bg radius table-hover">';
	tbHtml += '<thead>';
	tbHtml += '<tr>';
	tbHtml += '<th style="width: 20%;">赠品编号</th>';
	tbHtml += '<th style="width: 25%;">赠品名称</th>';
	tbHtml += '<th style="width: 25%;">供应商</th>';
	tbHtml += '<th style="width: 10%;">剩余库存</th>';
	tbHtml += '<th style="width: 10%;">赠品数量</th>';
	tbHtml += '<th style="width: 10%;">操作</th>';
	tbHtml += '</tr>';
	tbHtml += '</thead>';
	tbHtml += '<tbody id="rulePresentTbody_' + ruleNum + '"></tbody>';
	tbHtml += '</table>';
	tbHtml += '</div>';
	tbHtml += '</td>';
	tbHtml += '</tr>';
	tbHtml += '</table>';
	$("#ruleTd").append(tbHtml);
}

/**
 * 根据ID删除表单元素
 * @param id
 */
function deleteDomById(id) {
	layer.confirm("确定删除此数据？", function() {
		layer.closeAll('dialog');
		$("#" + id).remove();
		setBuyProNum();
		setfullProNum();
		setRulePresentNum();
	});
}

/**
 * 计算各个规则对应的赠品数量
 */
function setRulePresentNum() {
	$("tbody[id^='rulePresentTbody_']").each(function(){
		var ruleIndex = $(this).attr("id").replace("rulePresentTbody_", "");
		$("#rulePreNum_" + ruleIndex).text($(this).find("tr").length);
	});
}

/**
 * 计算满赠活动-参与活动的商品个数
 */
function setfullProNum() {
	$("#fullProNum").text($("#fullProTbody").find("tr").length);
}

/**
 * 买赠活动，计算参与活动的商品个数
 */
function setBuyProNum() {
	var idArr = [];
	// 查找以"buyProTd_id_"开头的TD
	$("#buyProTbody").find("td[id^='buyProTd_id_']").each(function() {
		var id = $(this).text();
		if(!isExists(idArr, id)) {
			idArr.push(id);
		}
	});
	$("#buyProNum").text(idArr.length);
}

/**
 * 根据值，查找数组中是否存在
 * @param arr
 * @param v
 * @returns {Boolean} true存在，false不存在
 */
function isExists(arr, v) {
	var flag = false;
	for(var i in arr) {
		if(arr[i] == v) {
			flag = true;
			break;
		}
	}
	return flag;
}

/**
 * 提交表单
 * @returns {Boolean}
 */
function sub_form() {
	var activityType = $("#activityType").val(); // 活动类型
	var name = $.trim($("#name").val()); // 活动名称
	var startDate = $("#startDate").val(); // 活动开始时间
	var endDate = $("#endDate").val(); // 活动截止时间
	if(name == "") {
		layer.alert("请填写活动名称！");
		return false;
	}
	if(startDate == "") {
		layer.alert("请选择开始时间！");
		return false;
	}
	if(endDate == "") {
		layer.alert("请选择结束时间！");
		return false;
	}
	var isShareBuyActive = $("input[name='isShareBuyActive']:checked").val(); // 是否与买赠活动同享
	var isShareFullActive = $("input[name='isShareFullActive']:checked").val(); // 是否与满赠活动同享
	var dec = $("#dec").val();
	var id = $("#activeId").val();
	var buyProInfo = {}; // key：TRID，value：商品编号_购买数量_赠品编号_赠品数量
	var data = {};
	data.activeType = activityType;
	data.name = name;
	data.startDate = startDate;
	data.endDate = endDate;
	data.isShareBuyActive = isShareBuyActive;
	data.isShareFullActive = isShareFullActive;
	data.dec = dec;
	if(id != "") { // 修改
		data.id = id;
	}
	
	var validatFlag = true;
	if(activityType == "4") { // 买赠活动
		var buyProTrs = $("#buyProTbody").find("tr");
		if(buyProTrs.length == 0) {
			layer.alert("请选择活动商品！");
			return false;
		}
		buyProTrs.css("background-color", ""); // 移除重复行颜色样式
		buyProTrs.each(function(index, ele) {
			var idFlag = $(this).attr("id").split("_")[1];
			var proId = $("#buyProTd_id_" + idFlag).text(); // 商品编号
			var saleNum = $("#buyPro_saleNum_" + idFlag).val(); // 购买数量
			var preId = $("#buyProTd_preId_" + idFlag).text(); // 赠品编号
			var preNum = $("#buyPro_preNum_" + idFlag).val(); // 赠品数量
			if(saleNum == "" || isNaN(saleNum)) {
				layer.alert("活动商品第" + (index + 1) + "行：请输入合法的购买数量！");
				return validatFlag = false;
			}
			if(preId == "") {
				layer.alert("活动商品第" + (index + 1) + "行：请选择赠品！");
				return validatFlag = false;
			}
			if(preNum == "" || isNaN(preNum)) {
				layer.alert("活动商品第" + (index + 1) + "行：请输入合法的赠品数量！");
				return validatFlag = false;
			}
			data["buyProList[" + index + "].product.id"] = proId;
			data["buyProList[" + index + "].buyNum"] = saleNum;
			data["buyProList[" + index + "].present.id"] = preId;
			data["buyProList[" + index + "].presentNum"] = preNum;
			buyProInfo[$(this).attr("id")] = proId + "_" + saleNum + "_" + preId + "_" + preNum;
		});
		if(!validatFlag) {
			return false;
		}
	} else if(activityType == "5") { // 满赠活动
		var fullActiveScope = $("input[name='fullActiveScope']:checked").val(); // 活动商品范围
		data.fullActiveScope = fullActiveScope;
		if(fullActiveScope == "2") { // 指定商品
			var fullProTrs = $("#fullProTbody").find("tr");
			if(fullProTrs.length == 0) {
				layer.alert("请选择活动商品！");
				return false;
			}
			fullProTrs.each(function(index, ele) {
				var idFlag = $(this).attr("id").split("_")[1];
				data["fullProList[" + index + "].product.id"] = $("#fullProTd_id_" + idFlag).text(); // 商品编号
			});
		}
		$("#ruleTd").find("table[name='ruleTb']").each(function(index, ele) {
			var idFlag = $(this).attr("id").split("_")[1];
			var orderPrice = $("#orderPrice_" + idFlag).val();
			if(orderPrice == "") {
				layer.alert("规则" + idFlag + "：请输入订单金额！");
				return validatFlag = false;
			}
			if(orderPrice == "" || isNaN(orderPrice)) {
				layer.alert("规则" + idFlag + "：请输入合法的订单金额！");
				return validatFlag = false;
			}
			data["fullPresentRule[" + index + "].orderMoney"] = orderPrice;
			
			var rulePreTrs = $("#rulePresentTbody_" + idFlag).find("tr");
			if(rulePreTrs.length == 0) {
				layer.alert("规则" + idFlag + "：请选择赠品！");
				return validatFlag = false;
			}
			rulePreTrs.each(function(index2, ele) {
				var trFlag = $(this).attr("id").split("_")[2];
				var preId = $("#rulePresentTd_id_" + idFlag + "_" + trFlag).text();
				var preNum = $("#rulePresent_preNum_" + idFlag + "_" + trFlag).val();
				if(preNum == "" || isNaN(preNum)) {
					layer.alert("规则" + idFlag + "-赠品信息第" + (index2 + 1) + "行：赠品数量不正确！");
					return validatFlag = false;
				}
				data["fullPresentRule[" + index + "].rulePresentList["+index2+"].present.id"] = preId;
				data["fullPresentRule[" + index + "].rulePresentList["+index2+"].presentSum"] = preNum;
			});
			if(!validatFlag) return false;
		});
		if(!validatFlag) {
			return false;
		}
	}
	// 买赠需校验是否有一样的数据
	if(activityType == "4") {
		for(var trId in buyProInfo) {
			for(var trId2 in buyProInfo) {
				if(trId != trId2 && buyProInfo[trId] == buyProInfo[trId2]) {
					// 重复数据高亮显示
					$("#" + trId).css("background-color", "#f2dcdb");
					$("#" + trId2).css("background-color", "#f2dcdb");
					validatFlag = false;
				}
			}
		}
	}
	if(activityType == "4" && !validatFlag) {
		layer.confirm("存在重复数据（高亮显示），是否保存？", function() {
			ajaxRequest(data);
		});
	} else {
		ajaxRequest(data);
	}
}

function ajaxRequest(data) {
	var index = layer.load(2);
	$.ajax({
		type: 'post',
		url: $("#save_form").attr("action"),
		data: data,
		dataType: 'text',
		success: function(data) {
			if(data == "success") {
				layer.msg("保存成功", {icon : 1, time : 500}, function() {
					parent.location.reload();
					closeLayer();
				});
			} else {
				layer.alert(data);
			}
			layer.close(index);
		},
		error: function() {
			layer.alert("操作失败!");
			layer.close(index);
		}
	});
}

/**
 * 活动类型改变时触发
 */
function activeTypeChange() {
	var activityType = $("#activityType").val();
	if (activityType == 4) { // 买赠活动
		$(".manzeng-zhiding").hide();
		$(".manzeng").hide();
		$(".maizeng").show();
	} else if (activityType == 5) { // 满赠活动
		$(".manzeng-zhiding").hide();
		$(".maizeng").hide();
		$(".manzeng").show();
		fullActiveScopeChecked();
	}
}

function fullActiveScopeChecked() {
	var v = $("input[type='radio'][name='fullActiveScope']:checked").val();
	if(v == "1") { // 全部商品
		$(".manzeng-zhiding").hide();
	} else if (v == "2") { // 指定商品
		$(".manzeng-zhiding").show();
	}
}

/**
 * 打开弹出层
 * @param title 标题
 * @param url 访问URL
 * @return
 */
function openLayer(title, url) {
	if(url.indexOf("?") > -1) {
		url += "&pWindowName=" + window.name;
	} else {
		url += "?pWindowName=" + window.name;
	}
	var index = parent.layer.open({
		resize: true,
		type: 2,
		title: title,
		content: url,
		area: [(document.body.clientWidth > 1000 ? 1000 : document.body.clientWidth) + "px", (document.body.clientHeight > 600 ? 600 : document.body.clientHeight) + "px"]
    });
	// 最大化
	parent.layer.full(index);
    return index;
}

/**
 * 关闭窗口
 */
function closeLayer() {
	var index = parent.layer.getFrameIndex(window.name);
	parent.layer.close(index);
}